package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    @Resource
    private CacheManager cacheManager;

    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
//        log.info("setmeal=={}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("添加套餐成功");
    }

    /**
     * 套餐信息分页查询
     * @param page 当前页码
     * @param pageSize 每一页显示的条数
     * @param name 查询信息名称，可能为空
     * @return
     */
    @GetMapping("/page")
    @Transactional
    public R<Page> page(int page, int pageSize, String name) {
        // 创建分页对象Page，这个分页中没有所属的套餐分类名称，需要整合
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        // 创建整合信息页
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);
        // 创建比较器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Setmeal::getName, name);
        // 定义排序规则
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        // 返回分页信息
        setmealService.page(pageInfo, queryWrapper);
        // 整合信息拷贝， 因为Setmeal，SetmealDto泛型不同，所以records需要手动处理
        BeanUtils.copyProperties(pageInfo, setmealDtoPage, "records");

        // 泛型处理
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> setmealList = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();
            // 根据id获取套餐分类名称
            Category category = categoryService.getById(categoryId);
            if(category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(setmealList);
        return R.success(setmealDtoPage);
    }

    /**
     * 删除套餐及其下面的菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> remove(@RequestParam List<Long> ids) {
//        log.info("ids=>{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐删除成功");
    }

    /**
     * 根据ids修改套餐信息的售卖状态
     * @param st
     * @param ids
     * @return
     */
    @PostMapping("/status/{st}")
    public R<String> status(@PathVariable Integer st, @RequestParam List<Long> ids) {
//        log.info("st{}, ids{}", st, ids);
        // 创建比较器
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId, ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus, st ^ 1);
        // 修改状态
        List<Setmeal> list = setmealService.list(lambdaQueryWrapper);
        list.stream().map((item) -> {
            item.setStatus(st);
            return item;
        }).collect(Collectors.toList());
        // 更新状态
        setmealService.updateBatchById(list);
        return R.success("状态修改成功");
    }

    /**
     * 根据套餐分类id，查询对应分类下的所有菜品并返回
     * 为套餐添加提供服务
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.getStatus")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        log.info("Setmeal=>{}", setmeal);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(queryWrapper);
        stopWatch.stop();
        log.info("消耗时间===>{}", stopWatch.getLastTaskTimeMillis());
        return R.success(list);
    }

    /**
     * 后台点击保存后，修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> put(@RequestBody SetmealDto setmealDto) {
        // 更新套餐信息，还要更新setmealDish中的信息。
        setmealService.updateWithDish(setmealDto);
        return R.success("套餐信息修改成功");
    }

    /**
     * 修改后台套餐信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable("id") Long id) {
        log.info("id={}", id);
        // 返回id对应的套餐信息，此时的套餐信息中，不包含菜品信息
        Setmeal setmeal = setmealService.getById(id);
        // 创建条件查询
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
        // 查询该套餐下的菜品信息
        List<SetmealDish> setmealDish = setmealDishService.list(queryWrapper);
        // 属性赋值
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        // dto赋值
        setmealDto.setSetmealDishes(setmealDish);
        return R.success(setmealDto);
    }



    /**
     * 前端页面，点击套餐后，根据套餐id，显示套餐下的菜品
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<Dish>> dishList(@PathVariable("id") Long id) {
        log.info("dish_id = {}", id);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        queryWrapper.orderByDesc(SetmealDish::getUpdateTime);

        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        List<Long> ids = setmealDishes.stream().map((item) -> {
            return item.getDishId();
        }).collect(Collectors.toList());

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(Dish::getId, ids);
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        return R.success(list);
    }
}
